package com.csun.dsms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.config.properties.CsunProperties;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.mapper.*;
import com.csun.dsms.model.domain.DsmsResource;
import com.csun.dsms.model.domain.TicketProblemPercent;
import com.csun.dsms.model.education.JyProblemDepartment;
import com.csun.dsms.model.education.JyProblemDetail;
import com.csun.dsms.model.education.JyProblemReport;
import com.csun.dsms.model.process.*;
import com.csun.dsms.model.vo.ticketproblem.TicketProblemPercentVo;
import com.csun.dsms.service.TicketProblemInfoService;
import com.csun.dsms.utils.MimeTypeUtil;
import com.csun.dsms.utils.OSSManageUtil;
import com.csun.dsms.utils.SourceType;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TicketProblemInfoServiceImpl implements TicketProblemInfoService {
    @Resource
    private TicketProblemInfoMapper ticketProblemInfoMapper;

    @Resource
    private ProcessNodeMapper processNodeMapper;

    @Resource
    private ProcessMouldMapper processMouldMapper;

    @Resource
    private OSSManageUtil ossManageUtil;

    @Resource
    private CsunProperties csunProperties;

    @Resource
    private JyProblemReportMapper jyProblemReportMapper;

    @Resource
    private JyProblemDetailMapper jyProblemDetailMapper;

    @Resource
    private ProblemSummaryInfoMapper problemSummaryInfoMapper;

    @Resource
    private JyProblemDepartmentMapper jyProblemDepartmentMapper;

    @Resource
    private DepartmentInfoMapper departmentInfoMapper;

    @Resource
    private TicketProblemPercentMapper ticketProblemPercentMapper;


    @Override
    public Wrapper<Object> addTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            String mouldName = ticketProblemInfo.getMouldName();
            Integer summaryId = ticketProblemInfo.getSummaryId();
            String processHandlerDepartment = ticketProblemInfo.getProcessHandlerDepartment();
            if (summaryId==null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "问题汇总id不能为空");
            }
            if (StrUtil.isNotBlank(processHandlerDepartment)) {
                DepartmentInfo queryDepartmentInfo = new DepartmentInfo();
                queryDepartmentInfo.setDepartmentName(processHandlerDepartment);
                List<DepartmentInfo> departmentInfoList = departmentInfoMapper.select(queryDepartmentInfo);
                if (CollectionUtil.isNotEmpty(departmentInfoList)) {
                    String areaName = departmentInfoList.get(0).getAreaName();
                    ticketProblemInfo.setAreaName(areaName);
                }
            }
            ProblemSummaryInfo problemSummaryInfo = problemSummaryInfoMapper.selectByPrimaryKey(summaryId);
            if (problemSummaryInfo == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "问题汇总不存在");
            }
            String summaryNo = problemSummaryInfo.getSummaryNo();
            TicketProblemInfo queryTicketProblemInfo = new TicketProblemInfo();
            queryTicketProblemInfo.setSummaryId(summaryId);
            List<TicketProblemInfo> existTicketProblemInfoList = ticketProblemInfoMapper.select(queryTicketProblemInfo);
            if (CollectionUtil.isNotEmpty(existTicketProblemInfoList)){
                Collections.sort(existTicketProblemInfoList, Comparator.comparing(TicketProblemInfo::getTicketNo).reversed());
                String lastTicketNo = existTicketProblemInfoList.get(0).getTicketNo();
                ticketProblemInfo.setTicketNo(Convert.toStr(Convert.toInt(lastTicketNo) + 1));
            }else{
                String ticketNo = summaryNo + "0001";
                ticketProblemInfo.setTicketNo(ticketNo);
            }

//            if (StrUtil.isBlank(mouldName)) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "模板名称不能为空");
//            }

            Date date = new Date();
            ProcessNode processNode = new ProcessNode();
            ProcessMould processMould = new ProcessMould();
            processMould.setName(mouldName);
//            List<ProcessMould> processMouldList = processMouldMapper.select(processMould);
//            if (CollectionUtil.isEmpty(processMouldList)) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "未找到模板");
//            }
//            Collections.sort(processMouldList, Comparator.comparingInt(ProcessMould::getSort));
//            String nodeName = processMouldList.get(0).getNodeName();
            String nodeName = ticketProblemInfo.getNodeName();
            ticketProblemInfo.setCreatedTime(date);
            ticketProblemInfoMapper.insert(ticketProblemInfo);
            Integer id = ticketProblemInfo.getId();

            processNode.setTicketId(id);
            processNode.setNodeContent(ticketProblemInfo.getContent());
            processNode.setNodeOwnerId(ticketProblemInfo.getProcessHandlerId());
            processNode.setNodeOwnerName(ticketProblemInfo.getProcessHandlerName());
            processNode.setNodeStatus("1");
            processNode.setNodeName(nodeName);
            processNode.setAnnexFile(ticketProblemInfo.getAnnexFile());
            processNode.setCreatedTime(date);
            ticketProblemInfo.setProcessNodeName(nodeName);
            processNodeMapper.insert(processNode);
            //addTaskNumber(ticketProblemInfo,"field1");
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> addTicketProblemInfoList(JSONObject reqJson) {
        JSONArray dataList = reqJson.getJSONArray("data");
        if (CollectionUtil.isNotEmpty(dataList)) {
            for (int i = 0; i < dataList.size(); i++) {
                try {
                    TicketProblemInfo ticketProblemInfo = dataList.getObject(i, TicketProblemInfo.class);
                    addTicketProblemInfo(ticketProblemInfo);
                } catch (Exception e) {
                    continue;
                }
            }
        }
        return WrapMapper.ok();
    }

    @Override
    public Wrapper<Object> updateTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            ticketProblemInfoMapper.updateByPrimaryKeySelective(ticketProblemInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> deleteTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            ticketProblemInfoMapper.deleteByPrimaryKey(id);
            return WrapMapper.ok();
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> selectTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            return WrapMapper.ok(ticketProblemInfoMapper.selectByPrimaryKey(id));
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> selectTicketProblemInfoList(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            List<Object> resList = CollectionUtil.newArrayList();
            String group = reqJson.getString("group");
            String areaName = reqJson.getString("areaName");
            String processHandlerDepartment = reqJson.getString("processHandlerDepartment");
            String prominentIssue = reqJson.getString("prominentIssue");
            String issueType = reqJson.getString("issueType");

            TicketProblemInfo queryTicketProblemInfo = new TicketProblemInfo();
            if (StrUtil.isNotBlank(areaName)){
                queryTicketProblemInfo.setAreaName(areaName);
            }
            if (StrUtil.isNotBlank(processHandlerDepartment)){
                queryTicketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
            }
            if (StrUtil.isNotBlank(prominentIssue)){
                queryTicketProblemInfo.setProminentIssue(prominentIssue);
            }
            if (StrUtil.isNotBlank(issueType)){
                queryTicketProblemInfo.setIssueType(issueType);
            }

            List<TicketProblemInfo> ticketProblemInfos = ticketProblemInfoMapper.select(queryTicketProblemInfo);
            if ("areaName".equals(group)){
                List<String> areaNameList = ticketProblemInfos.stream().map(TicketProblemInfo::getAreaName).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String area : areaNameList) {
                    JSONObject json = new JSONObject();
                    List<TicketProblemInfo> collect = ticketProblemInfos.stream().filter(TicketProblemInfo -> TicketProblemInfo.getAreaName() != null && TicketProblemInfo.getAreaName().equals(area)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream().filter(ticketProblemInfo -> ticketProblemInfo.getStatus() != null && !ticketProblemInfo.getStatus().equals("1")).count();

                    json.put("areaName",area);
                    json.put("field1",field1);
                    json.put("field2",Convert.toInt(field2));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }else if ("processHandlerDepartment".equals(group)){
                List<String> processHandlerDepartmentList = ticketProblemInfos.stream().map(TicketProblemInfo::getProcessHandlerDepartment).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String department : processHandlerDepartmentList) {
                    JSONObject json = new JSONObject();
                    List<TicketProblemInfo> collect = ticketProblemInfos.stream().filter(TicketProblemInfo -> TicketProblemInfo.getProcessHandlerDepartment() != null && TicketProblemInfo.getProcessHandlerDepartment().equals(department)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream().filter(ticketProblemInfo -> ticketProblemInfo.getStatus() != null && !ticketProblemInfo.getStatus().equals("1")).count();

                    json.put("areaName",department);
                    json.put("field1",field1);
                    json.put("field2",Convert.toInt(field2));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }

            return WrapMapper.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> selectTicketProblemInfoPage(JSONObject reqJson) {
        try {
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
            PageHelper.startPage(pageNum, pageSize);
            TicketProblemInfo ticketProblemInfo = new TicketProblemInfo();
            String ticketNo = reqJson.getString("ticketNo");
            if (StrUtil.isNotBlank(ticketNo)) {
                ticketProblemInfo.setTicketNo(ticketNo);
            }
            String content = reqJson.getString("content");
            if (StrUtil.isNotBlank(content)) {
                ticketProblemInfo.setContent(content);
            }
            String riskLevel = reqJson.getString("riskLevel");
            if (StrUtil.isNotBlank(riskLevel)) {
                ticketProblemInfo.setRiskLevel(riskLevel);
            }
            String status = reqJson.getString("status");
            if (StrUtil.isNotBlank(status)) {
                ticketProblemInfo.setStatus(status);
            }
            String isEvaluate = reqJson.getString("isEvaluate");
            if (StrUtil.isNotBlank(isEvaluate)) {
                ticketProblemInfo.setIsEvaluate(isEvaluate);
            }
            String processHandlerDepartment = reqJson.getString("processHandlerDepartment");
            if (StrUtil.isNotBlank(processHandlerDepartment)) {
                ticketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
            }
            String processHandlerName = reqJson.getString("processHandlerName");
            if (StrUtil.isNotBlank(processHandlerName)) {
                ticketProblemInfo.setProcessHandlerName(processHandlerName);
            }
            String processNodeName = reqJson.getString("processNodeName");
            if (StrUtil.isNotBlank(processNodeName)) {
                ticketProblemInfo.setProcessNodeName(processNodeName);
            }
            String issueType = reqJson.getString("issueType");
            if (StrUtil.isNotBlank(issueType)) {
                ticketProblemInfo.setIssueType(issueType);
            }
            String issueCategory = reqJson.getString("issueCategory");
            if (StrUtil.isNotBlank(issueCategory)) {
                ticketProblemInfo.setIssueCategory(issueCategory);
            }
            String prominentIssue = reqJson.getString("prominentIssue");
            if (StrUtil.isNotBlank(prominentIssue)) {
                ticketProblemInfo.setProminentIssue(prominentIssue);
            }
            String applicantName = reqJson.getString("applicantName");
            if (StrUtil.isNotBlank(applicantName)) {
                ticketProblemInfo.setApplicantName(applicantName);
            }
            String applicantPhoneNumber = reqJson.getString("applicantPhoneNumber");
            if (StrUtil.isNotBlank(applicantPhoneNumber)) {
                ticketProblemInfo.setApplicantPhoneNumber(applicantPhoneNumber);
            }
            String processHandlerId = reqJson.getString("processHandlerId");
            if (StrUtil.isNotBlank(processHandlerId)) {
                ticketProblemInfo.setProcessHandlerId(processHandlerId);
            }
            String issueSubCategory = reqJson.getString("issueSubCategory");
            if (StrUtil.isNotBlank(issueSubCategory)) {
                ticketProblemInfo.setIssueSubCategory(issueSubCategory);
            }
            String appealName = reqJson.getString("appealName");
            if (StrUtil.isNotBlank(appealName)) {
                ticketProblemInfo.setAppealName(appealName);
            }
            String appealPhoneNumber = reqJson.getString("appealPhoneNumber");
            if (StrUtil.isNotBlank(appealPhoneNumber)) {
                ticketProblemInfo.setAppealPhoneNumber(appealPhoneNumber);
            }
            String dataResource = reqJson.getString("dataResource");
            if (StrUtil.isNotBlank(dataResource)) {
                ticketProblemInfo.setDataResource(dataResource);
            }

            List<TicketProblemInfo> list = ticketProblemInfoMapper.selectData(ticketProblemInfo);
            for (TicketProblemInfo info : list) {
                TicketProblemPercent ticketProblemPercentQuery = new TicketProblemPercent();
                ticketProblemPercentQuery.setTicketProblemInfoId(info.getId());
                List<TicketProblemPercent> ticketProblemPercentList = ticketProblemPercentMapper.select(ticketProblemPercentQuery);
                List<TicketProblemPercentVo> ticketProblemPercentVoList = ticketProblemPercentList.stream().map(ticketProblemPercent -> {
                    TicketProblemPercentVo ticketProblemPercentVo = new TicketProblemPercentVo();
                    BeanUtils.copyProperties(ticketProblemPercent, ticketProblemPercentVo);
                    return ticketProblemPercentVo;
                }).collect(Collectors.toList());
                info.setTicketProblemPercentVoList(ticketProblemPercentVoList);
            }
            Collections.sort(list, Comparator.comparing(TicketProblemInfo::getId).reversed());
            return WrapMapper.ok(new PageInfo<>(list));
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> processIssuance(JSONObject reqJson) {
        try {
            DateTime date = DateUtil.date();
            Integer id = reqJson.getInteger("id");
            String processNodeName = reqJson.getString("processNodeName");
            String completeDescription = reqJson.getString("completeDescription");
            String processHandlerId = reqJson.getString("processHandlerId");
            String processHandlerName = reqJson.getString("processHandlerName");
            String processHandlerDepartment = reqJson.getString("processHandlerDepartment");
            String annexFile = reqJson.getString("annexFile");
//            String mouldName = reqJson.getString("mouldName");
            String rectificationObjective = reqJson.getString("rectificationObjective");
            String rectificationMeasure = reqJson.getString("rectificationMeasure");
            String acceptanceCriteria = reqJson.getString("acceptanceCriteria");
            Date completeDeadline = reqJson.getDate("completeDeadline");
            String issueType = reqJson.getString("issueType");
            JSONArray participantsList = reqJson.getJSONArray("participantsList");
            Date meetDeadline = reqJson.getDate("meetDeadline");
            Date meetTime = reqJson.getDate("meetTime");
            JSONArray actuallyParticipantsList = reqJson.getJSONArray("actuallyParticipantsList");

            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
//            if (StrUtil.isBlank(mouldName)) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "模板名称不能为空");
//            }
            TicketProblemInfo queryTicketProblemInfo = ticketProblemInfoMapper.selectByPrimaryKey(id);
            if (queryTicketProblemInfo == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "工单不存在");
            }

//            ProcessMould processMould = new ProcessMould();
//            processMould.setName(mouldName);
//            List<ProcessMould> processMouldList = processMouldMapper.select(processMould);
//            if (processMouldList == null) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "模板不存在");
//            }
//            Collections.sort(processMouldList, Comparator.comparingInt(ProcessMould::getSort));

//            String processNodeName = null;
            ProcessNode processNode = new ProcessNode();
            ProcessNode queryProcessNode = new ProcessNode();
            queryProcessNode.setTicketId(id);
            List<ProcessNode> processNodeList = processNodeMapper.select(queryProcessNode);
            if (CollectionUtil.isNotEmpty(processNodeList)) {
                Collections.sort(processNodeList, Comparator.comparing(ProcessNode::getCreatedTime).reversed());
                ProcessNode processNodeOld = processNodeList.get(0);
                String nodeName = processNodeOld.getNodeName();
                processNodeOld.setEndTime(date);
                processNodeOld.setNodeStatus("0");
                processNodeMapper.updateByPrimaryKey(processNodeOld);
                processNode.setParentId(processNodeOld.getId());

//                String nextNodeName = null;
//                if (StrUtil.isNotBlank(nodeName)) {
//                    Integer sort = processMouldList.stream().filter(mould -> mould.getNodeName().equals(nodeName)).collect(Collectors.toList()).get(0).getSort();
//                    List<ProcessMould> processMouldNextList = processMouldList.stream().filter(mould -> mould.getSort() == sort + 1).collect(Collectors.toList());
//                    if (CollectionUtil.isNotEmpty(processMouldNextList)) {
//                        nextNodeName = processMouldNextList.get(0).getNodeName();
//                    }
//                }
//                processNodeName = nextNodeName;
            }
            processNode.setTicketId(id);
            processNode.setNodeName(processNodeName);
            processNode.setNodeContent(completeDescription);
            processNode.setNodeOwnerId(processHandlerId);
            processNode.setNodeOwnerName(processHandlerName);
            processNode.setDepartment(processHandlerDepartment);
            processNode.setAnnexFile(annexFile);
            processNode.setNodeStatus("1");
            processNode.setCreatedTime(date);
            if(CollectionUtil.isNotEmpty(participantsList)){
                queryTicketProblemInfo.setParticipants(CollectionUtil.join(participantsList,","));
                processNode.setParticipants(CollectionUtil.join(participantsList,","));
            }
            if(meetDeadline != null){
                queryTicketProblemInfo.setMeetDeadline(meetDeadline);
                processNode.setMeetDeadline(meetDeadline);
            }
            if(meetTime != null){
                queryTicketProblemInfo.setMeetTime(meetTime);
                processNode.setMeetTime(meetTime);
            }
            if(CollectionUtil.isNotEmpty(actuallyParticipantsList)){
                queryTicketProblemInfo.setActuallyParticipants(CollectionUtil.join(actuallyParticipantsList,","));
                processNode.setActuallyParticipants(CollectionUtil.join(actuallyParticipantsList,","));
            }
            processNodeMapper.insert(processNode);

            if(StrUtil.isNotBlank(processHandlerId)){
                queryTicketProblemInfo.setProcessHandlerId(processHandlerId);
            }
            if(StrUtil.isNotBlank(processHandlerName)){
                queryTicketProblemInfo.setProcessHandlerName(processHandlerName);
            }
            if(StrUtil.isNotBlank(processNodeName)){
                queryTicketProblemInfo.setProcessNodeName(processNodeName);
            }
            if(StrUtil.isNotBlank(processHandlerDepartment)){
                queryTicketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
            }
            if(StrUtil.isNotBlank(completeDescription)){
                queryTicketProblemInfo.setCompleteDescription(completeDescription);
            }
            if(StrUtil.isNotBlank(rectificationObjective)){
                queryTicketProblemInfo.setRectificationObjective(rectificationObjective);
            }
            if(StrUtil.isNotBlank(rectificationMeasure)){
                queryTicketProblemInfo.setRectificationMeasure(rectificationMeasure);
            }
            if(StrUtil.isNotBlank(acceptanceCriteria)){
                queryTicketProblemInfo.setAcceptanceCriteria(acceptanceCriteria);
            }
            if(completeDeadline != null){
                queryTicketProblemInfo.setCompleteDeadline(completeDeadline);
            }
            if (issueType != null){
                queryTicketProblemInfo.setIssueType(issueType);
            }

            ticketProblemInfoMapper.updateByPrimaryKey(queryTicketProblemInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> processBack(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            TicketProblemInfo queryTicketProblemInfo = ticketProblemInfoMapper.selectByPrimaryKey(id);
            if (queryTicketProblemInfo == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "工单不存在");
            }
            queryTicketProblemInfo.setStatus("2");
            queryTicketProblemInfo.setEndTime(DateUtil.date());
            ticketProblemInfoMapper.updateByPrimaryKey(queryTicketProblemInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> queryNodeList(JSONObject reqJson) {
        try {
            Integer id = reqJson.getInteger("ticket_id");
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            ProcessNode queryProcessNode = new ProcessNode();
            queryProcessNode.setTicketId(id);
            List<ProcessNode> processNodeList = processNodeMapper.select(queryProcessNode);
            return WrapMapper.ok(processNodeList);
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> updateNodeList(ProcessNode processNode) {
        try {
            Integer id = processNode.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            processNodeMapper.updateByPrimaryKeySelective(processNode);
            return WrapMapper.ok();
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> processEnd(JSONObject reqJson) {
        try {
            Integer id = reqJson.getInteger("id");
            String evaluateContent = reqJson.getString("evaluateContent");
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            TicketProblemInfo queryTicketProblemInfo = ticketProblemInfoMapper.selectByPrimaryKey(id);
            if (queryTicketProblemInfo == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "工单不存在");
            }
            DateTime date = DateUtil.date();
            ProcessNode queryProcessNode = new ProcessNode();
            queryProcessNode.setTicketId(id);
            List<ProcessNode> processNodeList = processNodeMapper.select(queryProcessNode);
            if (CollectionUtil.isNotEmpty(processNodeList)) {
                Collections.sort(processNodeList, Comparator.comparing(ProcessNode::getCreatedTime).reversed());
                ProcessNode processNode = processNodeList.get(0);
                processNode.setNodeStatus("2");
                processNode.setEndTime(date);
                processNodeMapper.updateByPrimaryKey(queryProcessNode);
            } else {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "节点不存在");
            }
            queryTicketProblemInfo.setEvaluateTime(date);
            queryTicketProblemInfo.setIsEvaluate("1");
            queryTicketProblemInfo.setEvaluateScore("0");
            queryTicketProblemInfo.setEvaluateContent(evaluateContent);
            queryTicketProblemInfo.setEndTime(date);
            queryTicketProblemInfo.setStatus("0");
            ticketProblemInfoMapper.updateByPrimaryKey(queryTicketProblemInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> uploadFile(HttpServletRequest request) {
        try {
            /* 获取文件描述参数 */
            String remark = request.getParameter("remark");
            List<DsmsResource> resources = new ArrayList<DsmsResource>();
            /* 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）*/
            CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            /* 检查form中是否有enctype="multipart/form-data" */
            if(multipartResolver.isMultipart(request)) {
                /* 将request变成多部分request */
                MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;

                /* 获取multiRequest 中所有的文件名*/
                Iterator iter = multiRequest.getFileNames();
                String timedate  = Convert.toStr(DateUtil.current());	// 时间戳,避免文件覆盖

                while(iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if(file != null) {
                        /* 文件属性获取 */
                        SourceType sourceType = MimeTypeUtil.getSourceType(file.getContentType());
                        /* MultipartFile 转 File */
                        File f=File.createTempFile("tmp", null);
                        file.transferTo(f);
                        f.deleteOnExit();
                        /* OSS文件上传 */
                        ossManageUtil.uploadFile(f, file.getOriginalFilename(), file.getContentType(), sourceType
                                .getSourceTypePath() + "/" + timedate);
                        /* 保存上传的文件属性 */
                        DsmsResource r = new DsmsResource();
                        r.setResourceName(file.getOriginalFilename());
                        r.setResourcePath(csunProperties.getAliyun().getOss().getAccessUrl() + "/"
                                + sourceType.getSourceTypePath() + "/" + timedate + "/" + file.getOriginalFilename());
                        if (StrUtil.isNotBlank(remark)) {
                            r.setRemark(remark);
                        }
                        r.setResourceTypeId(Integer.parseInt(sourceType.getSourceTypeId()));
                        resources.add(r);
                    }
                }
            }
            return WrapMapper.ok(resources);
        } catch (Exception e) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public void downTicketProblemExcelData(HttpServletResponse response,JSONObject reqJson) {
        try {
            String prominentIssue = reqJson.getString("prominentIssue");
            List<String> row = CollUtil.newArrayList("突出问题类型", "问题内容", "问题来源", "来源描述",
                    "完成时限", "完成要求", "牵头单位","责任单位","备注");
            List<List<String>> rows = CollUtil.newArrayList(row, CollUtil.newArrayList());
            ExcelWriter writer = ExcelUtil.getWriter(true);
            writer.write(rows, true);

            //设置宽度20
            for (int i = 0; i < row.size(); i++) {
                writer.setColumnWidth(i, 20);
            }
            CellStyle dateStyle = writer.createCellStyle();
            DataFormat dataFormat = writer.getWorkbook().createDataFormat();
            dateStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); // 设置日期格式
            writer.setColumnStyle(5, dateStyle);

            CellRangeAddressList region0 = new CellRangeAddressList(1, 1000, 0, 0);
            writer.addSelect(region0,prominentIssue);

            ProblemSummaryInfo queryProblemSummaryInfo = new ProblemSummaryInfo();
            queryProblemSummaryInfo.setProminentIssue(prominentIssue);
            List<ProblemSummaryInfo> jyProblemDetails = problemSummaryInfoMapper.select(queryProblemSummaryInfo);
            if(CollectionUtil.isNotEmpty(jyProblemDetails)){
                ProblemSummaryInfo problemSummaryInfo = jyProblemDetails.get(0);
                String leadUnit = problemSummaryInfo.getLeadUnit();
                CellRangeAddressList region6 = new CellRangeAddressList(1, 1000, 6, 6);
                writer.addSelect(region6,leadUnit);
            }

            CellRangeAddressList region3 = new CellRangeAddressList(1, 1000, 2, 2);
            writer.addSelect(region3,"上级交办","群众投诉","干部自查");



            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=ExcelData.xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (Exception e) {
            log.error("下载模板数据报错", e);
        }
    }

    @Override
    public Wrapper<Object> importTicketProblemInfo(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> ExcelList = reader.readAll();
            if (CollectionUtil.isEmpty(ExcelList)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "Excel不能为空！");
            }
            DateTime date = DateUtil.date();
            for (Map<String, Object> map : ExcelList) {
                TicketProblemInfo ticketProblemInfo = new TicketProblemInfo();
                ProcessNode processNode = new ProcessNode();

                String prominentIssue = Convert.toStr(map.get("突出问题类型"));
                String content = Convert.toStr(map.get("问题内容"));
                String dataResource = Convert.toStr(map.get("问题来源"));
                String resourceDescription = Convert.toStr(map.get("来源描述"));
                Date completeDeadline = Convert.toDate(map.get("完成时限"));
                String completeDescription = Convert.toStr(map.get("完成要求"));
                String remark = Convert.toStr(map.get("备注"));
                String leadUnit = Convert.toStr(map.get("牵头单位"));
                String processHandlerDepartment = Convert.toStr(map.get("责任单位"));
                if (StrUtil.isNotBlank(processHandlerDepartment)) {
                    DepartmentInfo queryDepartmentInfo = new DepartmentInfo();
                    queryDepartmentInfo.setDepartmentName(processHandlerDepartment);
                    DepartmentInfo departmentInfo = departmentInfoMapper.selectOne(queryDepartmentInfo);
                    if (departmentInfo!=null) {
                        String areaName = departmentInfo.getAreaName();
                        ticketProblemInfo.setAreaName(areaName);
                    }
                    ticketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
                    ticketProblemInfo.setProcessNodeName("待受理");
                    processNode.setDepartment(processHandlerDepartment);
                    processNode.setNodeName("待受理");
                }else{
                    ticketProblemInfo.setProcessNodeName("待分拨");
                    processNode.setNodeName("待分拨");
                }
                processNode.setRemark("系统导入");
                processNode.setNodeContent(completeDescription);
                processNode.setNodeStatus("1");

                ticketProblemInfo.setProminentIssue(prominentIssue);
                ticketProblemInfo.setTitle(prominentIssue);
                ticketProblemInfo.setContent(content);
                ticketProblemInfo.setDataResource(dataResource);
                ticketProblemInfo.setResourceDescription(resourceDescription);
                ticketProblemInfo.setCompleteDeadline(completeDeadline);
                ticketProblemInfo.setCompleteDescription(completeDescription);
                ticketProblemInfo.setRemark(remark);
                ticketProblemInfo.setLeadUnit(leadUnit);
                ticketProblemInfo.setRiskLevel("1");
                ticketProblemInfo.setCreatedTime(date);
                ticketProblemInfoMapper.insert(ticketProblemInfo);
                processNode.setTicketId(ticketProblemInfo.getId());
                processNode.setCreatedTime(date);
                processNodeMapper.insert(processNode);

            }
            return WrapMapper.ok();
        } catch (Exception e) {
            log.error("下载模板数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "下载模板数据报错");
        }
    }

    public void addTaskNumber(TicketProblemInfo ticketProblemInfo,String addField) {
        DecimalFormat df = new DecimalFormat("0.00%");
        String prominentIssue = ticketProblemInfo.getProminentIssue();
        String issueType = ticketProblemInfo.getIssueType();
        String areaName = ticketProblemInfo.getAreaName();
        String processHandlerDepartment = ticketProblemInfo.getProcessHandlerDepartment();
        if (StrUtil.isBlank(prominentIssue)) {
            return;
        }
        JyProblemReport queryJyProblemReport = new JyProblemReport();
        queryJyProblemReport.setProminentIssue(prominentIssue);
        List<JyProblemReport> jyProblemReports = jyProblemReportMapper.select(queryJyProblemReport);
        JyProblemDetail queryJyProblemDetail = new JyProblemDetail();
        queryJyProblemDetail.setProject(prominentIssue);
        queryJyProblemDetail.setContent(issueType);
        List<JyProblemDetail> jyProblemDetails = jyProblemDetailMapper.select(queryJyProblemDetail);
        JyProblemDepartment queryJyProblemDepartment = new JyProblemDepartment();
        queryJyProblemDepartment.setDepartment(areaName);
        queryJyProblemDepartment.setContent(issueType);
        queryJyProblemDepartment.setProject(prominentIssue);
        queryJyProblemDepartment.setDepartment(processHandlerDepartment);
        List<JyProblemDepartment> jyProblemDepartments = jyProblemDepartmentMapper.select(queryJyProblemDepartment);
        if (CollectionUtil.isEmpty(jyProblemReports) || CollectionUtil.isEmpty(jyProblemDetails)) {
            return;
        }

        //部门数量更新
        List<JyProblemDepartment> regionyProblemDepartments = jyProblemDepartments.stream().filter(JyProblemDepartment -> JyProblemDepartment.getRegion().equals(areaName)).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(regionyProblemDepartments)) {
            JyProblemDepartment jyProblemDepartment = regionyProblemDepartments.get(0);
            String field1 = jyProblemDepartment.getField1();
            String field2 = jyProblemDepartment.getField2();
            if (addField.equals("field1")) {
                jyProblemDepartment.setField1(Convert.toStr(Convert.toInt(field1) + 1));
            } else if (addField.equals("field2")) {
                jyProblemDepartment.setField2(Convert.toStr(Convert.toInt(field2) + 1));
            }
            jyProblemDepartment.setField3(Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)) );
            jyProblemDepartmentMapper.updateByPrimaryKey(jyProblemDepartment);
        }else {
            JyProblemDepartment jyProblemDepartment = new JyProblemDepartment();
            jyProblemDepartment.setDepartment(areaName);
            jyProblemDepartment.setContent(issueType);
            jyProblemDepartment.setProject(prominentIssue);
            jyProblemDepartment.setDepartment(processHandlerDepartment);
            if (addField.equals("field1")) {
                jyProblemDepartment.setField1("1");
            } else if (addField.equals("field2")) {
                jyProblemDepartment.setField2("1");
            }
            String field1 = jyProblemDepartment.getField1();
            String field2 = jyProblemDepartment.getField2();
            jyProblemDepartment.setField3(Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)) );
            jyProblemDepartmentMapper.insert(jyProblemDepartment);
        }
        switch (prominentIssue) {
            case "优化政务环境":
                if (issueType.equals("工作作风不优")) {
                    List<JyProblemDetail> regionyProblemDetails = jyProblemDetails.stream().filter(JyProblemDetail -> JyProblemDetail.getRegion().equals(areaName)).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(regionyProblemDetails)) {
                        JyProblemDetail jyProblemDetail = regionyProblemDetails.get(0);
                        if (addField.equals("field1")) {
                            String field1 = jyProblemDetail.getField1();
                            jyProblemDetail.setField1(Convert.toStr(Convert.toInt(field1) + 1));
                        } else if (addField.equals("field2")) {
                            String field2 = jyProblemDetail.getField2();
                            jyProblemDetail.setField2(Convert.toStr(Convert.toInt(field2) + 1));
                        }
                        jyProblemDetailMapper.updateByPrimaryKey(jyProblemDetail);

                        List<JyProblemDetail> jyProblemDetailNews = jyProblemDetailMapper.select(queryJyProblemDetail);
                        double sum1 = jyProblemDetailNews.stream()
                                .map(JyProblemDetail::getField1)
                                .filter(Objects::nonNull)
                                .filter(str -> !str.isEmpty())
                                .mapToDouble(Double::parseDouble)
                                .sum();
                        double sum2 = jyProblemDetailNews.stream()
                                .map(JyProblemDetail::getField2)
                                .filter(Objects::nonNull)
                                .filter(str -> !str.isEmpty())
                                .mapToDouble(Double::parseDouble)
                                .sum();

                        JyProblemReport jyProblemReport = jyProblemReports.get(0);
                        String taskJson = jyProblemReport.getTask1Json();
                        JSONArray taskJsonArray = JSONArray.parseArray(taskJson);
                        for (int i = 0; i < taskJsonArray.size(); i++) {
                            JSONObject task1JsonObject = taskJsonArray.getJSONObject(i);
                            if (i == 0) {
                                task1JsonObject.put("value", sum1);
                            } else if (i == 1) {
                                task1JsonObject.put("value", sum2);
                            } else if (i == 2) {
                                task1JsonObject.put("value", sum1 == 0 ? "0.00%" : df.format((double) sum2 / sum1));
                            }
                        }
                        jyProblemReport.setTask1Json(taskJsonArray.toJSONString());
                        jyProblemReportMapper.updateByPrimaryKeySelective(jyProblemReport);
                    }
                } else if (issueType.equals("政务服务不优")) {
                    List<JyProblemDetail> regionyProblemDetails = jyProblemDetails.stream().filter(JyProblemDetail -> JyProblemDetail.getRegion().equals(areaName)).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(regionyProblemDetails)) {
                        JyProblemDetail jyProblemDetail = regionyProblemDetails.get(0);
                        if (addField.equals("field1")) {
                            String field1 = jyProblemDetail.getField1();
                            jyProblemDetail.setField1(Convert.toStr(Convert.toInt(field1) + 1));
                        } else if (addField.equals("field2")) {
                            String field2 = jyProblemDetail.getField2();
                            jyProblemDetail.setField2(Convert.toStr(Convert.toInt(field2) + 1));
                        }
                        jyProblemDetailMapper.updateByPrimaryKey(jyProblemDetail);

                        List<JyProblemDetail> jyProblemDetailNews = jyProblemDetailMapper.select(queryJyProblemDetail);
                        double sum1 = jyProblemDetailNews.stream()
                                .map(JyProblemDetail::getField1)
                                .filter(Objects::nonNull)
                                .filter(str -> !str.isEmpty())
                                .mapToDouble(Double::parseDouble)
                                .sum();
                        double sum2 = jyProblemDetailNews.stream()
                                .map(JyProblemDetail::getField2)
                                .filter(Objects::nonNull)
                                .filter(str -> !str.isEmpty())
                                .mapToDouble(Double::parseDouble)
                                .sum();

                        JyProblemReport jyProblemReport = jyProblemReports.get(0);
                        String taskJson = jyProblemReport.getTask2Json();
                        JSONArray taskJsonArray = JSONArray.parseArray(taskJson);
                        for (int i = 0; i < taskJsonArray.size(); i++) {
                            JSONObject task1JsonObject = taskJsonArray.getJSONObject(i);
                            if (i == 0) {
                                task1JsonObject.put("value", sum1);
                            } else if (i == 1) {
                                task1JsonObject.put("value", sum2);
                            } else if (i == 2) {
                                task1JsonObject.put("value", sum1 == 0 ? "0.00%" : df.format((double) sum2 / sum1));
                            }
                        }
                        jyProblemReport.setTask1Json(taskJsonArray.toJSONString());
                        jyProblemReportMapper.updateByPrimaryKeySelective(jyProblemReport);
                    }
                }
                break;
        }
    }
}